package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.ModelConfig;
import com.micro.ai.models.mapper.ModelConfigMapper;
import com.micro.ai.models.service.ModelConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 模型配置服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class ModelConfigServiceImpl extends ServiceImpl<ModelConfigMapper, ModelConfig> implements ModelConfigService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelConfig create(ModelConfig config) {
        if (config == null) {
            throw new BusinessException("M0000", "模型配置信息不能为空");
        }
        
        LocalDateTime now = LocalDateTime.now();
        config.setCreatedAt(now);
        config.setUpdatedAt(now);
        
        boolean success = this.save(config);
        if (!success) {
            throw new BusinessException("M0003", "保存模型配置失败");
        }
        
        log.info("创建模型配置成功: configId={}, configName={}", config.getId(), config.getConfigName());
        return config;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelConfig update(String id, ModelConfig config) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "配置ID不能为空");
        }
        if (config == null) {
            throw new BusinessException("M0000", "模型配置信息不能为空");
        }
        
        ModelConfig existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("M0002", "模型配置不存在: " + id);
        }
        
        config.setId(id);
        config.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(config);
        if (!success) {
            throw new BusinessException("M0003", "更新模型配置失败");
        }
        
        log.info("更新模型配置成功: configId={}", id);
        return config;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "配置ID不能为空");
        }
        
        ModelConfig config = this.getById(id);
        if (config == null) {
            throw new BusinessException("M0002", "模型配置不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("M0003", "删除模型配置失败");
        }
        
        log.info("删除模型配置成功: configId={}, configName={}", id, config.getConfigName());
    }

    @Override
    public Page<ModelConfig> pageQuery(int pageNum, int pageSize, String tenantId, String modelId, String status) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<ModelConfig> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ModelConfig> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(ModelConfig::getTenantId, tenantId);
        }
        if (StringUtils.hasText(modelId)) {
            query.eq(ModelConfig::getModelId, modelId);
        }
        if (StringUtils.hasText(status)) {
            query.eq(ModelConfig::getStatus, status);
        }
        
        query.orderByDesc(ModelConfig::getCreatedAt);
        return this.page(page, query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "配置ID不能为空");
        }
        
        ModelConfig config = this.getById(id);
        if (config == null) {
            throw new BusinessException("M0002", "模型配置不存在: " + id);
        }
        
        // 先取消同模型下的所有默认配置
        LambdaQueryWrapper<ModelConfig> query = new LambdaQueryWrapper<>();
        query.eq(ModelConfig::getModelId, config.getModelId())
             .eq(ModelConfig::getIsDefault, true)
             .ne(ModelConfig::getId, id);
        ModelConfig existingDefault = this.getOne(query);
        if (existingDefault != null) {
            existingDefault.setIsDefault(false);
            this.updateById(existingDefault);
        }
        
        // 设置当前配置为默认
        config.setIsDefault(true);
        boolean success = this.updateById(config);
        if (!success) {
            throw new BusinessException("M0003", "设置默认配置失败");
        }
        
        log.info("设置默认配置成功: configId={}", id);
    }

    @Override
    public ModelConfig getDefaultConfigByModelId(String modelId) {
        if (!StringUtils.hasText(modelId)) {
            return null;
        }
        
        LambdaQueryWrapper<ModelConfig> query = new LambdaQueryWrapper<>();
        query.eq(ModelConfig::getModelId, modelId)
             .eq(ModelConfig::getIsDefault, true)
             .eq(ModelConfig::getStatus, "active")
             .orderByDesc(ModelConfig::getCreatedAt)
             .last("LIMIT 1");
        
        return this.getOne(query);
    }
}

